$(function () {
	var param = parseUrlSearch();
	var cache = {};
	var status = '';
	$.init();
	renderCarList();

	$(document).on('click', '.minus', onMinus);
	$(document).on('click', '.add', onAdd);
	$(document).on('click', '.item-circle_wrap', onChoose);
	$(document).on('click', '.btn-del', onDel)
	$(document).on('click', '.btn-edit', onEdit);
	$(document).on('click', '.btn-sure', onSure);
	$(document).on('click', '.j-buy', onBuy);
	$(document).on('click', '.j-return', onReturn);
	$(document).on('click', '.j-look', onLook);

	function renderCarList() {
		fetchList(function(data) {
			var html = data.skus.reduce(function(memo, sku) {
				cache[sku.sku_code] = sku;
				return memo + getCarItemHtml(sku);
			}, '');
			$('.content ul').html(html);
		});
	}

	function fetchList (callback) {
		$.ajax({
			url: HOST + '/api/shopcart/sku/list',
			data: {
				openid: SELFID
			},
			success: function(res) {
				callback && callback(res.content);
			}
		});
	}

	function getCarItemHtml (data) {
		var skuspec = JSON.parse(data.sku_specification);
		var specs = '';
		for (var key in skuspec) {
			specs += (skuspec[key] + ' ');
		}
		return  '<li class="item" data-id="'+data.sku_code+'">\
					<div class="float-left item-circle_wrap"><div class="item_circle"></div></div>\
					<div class="float-left item_img j-look">\
						<img src="'+data.sku_image+'">\
					</div>\
					<div class="float-left item_info j-look">\
						<div class="tit">'+data.sku_name+'</div>\
						<div class="spec">'+specs+'</div>\
						<div class="date">'+moment(data.created_at*1000).format('YYYY-MM-DD hh:mm')+'</div>\
						<div class="pri"><span class="price" data-price="'+data.current_price+'">￥'+data.current_price+'</span> * <span class="amount" data-amount="'+data.qty+'">'+data.qty+'</span><span class="oPrice">'+(data.origin_price=='None'?'':('原价：'+data.origin_price))+'</span></div>\
					</div>\
					<div class="btn-wrap">\
						<span class="iconfont add">&#xe6b9;</span>\
						<span class="num" data-amount="'+data.qty+'">'+data.qty+'</span>\
						<span class="iconfont minus">&#xe6fe;</span>\
						<span class="btn-del j-del">删除</span>\
					</div>\
				</li>';
	}

	function onMinus (e) {
		var $num = $(e.currentTarget).closest('.btn-wrap').find('.num');
		var num = +$num.html();
		$num.html(num == 1 ? num : num - 1);
	}

	function onAdd (e) {
		var $num = $(e.currentTarget).closest('.btn-wrap').find('.num');
		var num = +$num.html();
		$num.html(num + 1);
	}

	function onChoose (e) {
		$(e.currentTarget).find('.item_circle').toggleClass('active');
		countTotal();
	}

	function countTotal () {
		var total = 0;
		$('.content .item_circle.active').forEach(function (item){
			var $item = $(item).closest('li');
			total += (+$item.find('.price').data('price'))*(+$item.find('.amount').data('amount'));
		});
		$('.buy-wrap .total').html('合计金额：'+new Number(total).toFixed(2)+' RMB').data('total', total);
	}

	function onEdit (e) {
		status = 'edit';
		$(e.currentTarget).hide();
		$('.btn-sure').show();
		$('.content .item').addClass('item_edit');
	}

	function collect () {
		var list = [];
		$('.item').forEach(function (item){
			var $item = $(item);
			var $num = $item.find('.num');
			list.push({
				skuCode: $item.data('id'),
				qty: $num.html() * 1 - $num.data('amount') * 1
			});
		});
		return list;
	}

	function onSure (e) {
		status = 'show';
		var list = collect();
		$.showPreloader('保存中');
		saveCar(list, function () {
			$.hidePreloader();
			$(e.currentTarget).hide();
			$('.btn-edit').show();
			$('.content .item').removeClass('item_edit');
			$('.content .item').forEach(function (item){
				var $item = $(item);
				var $num = $item.find('.num');
				var amount = +$num.html();
				$num.data('amount', amount);
				$item.find('.amount').html(amount).data('amount', amount);
			});
			countTotal();
		});
	}

	function onDel (e) {
		var $item = $(e.currentTarget).closest('.item');
		
		$.confirm('确定删除该商品吗？', function () {
			$.ajax({
				url: HOST + '/api/shopcart/sku/update',
				type: 'post',
				data: JSON.stringify({
					openid: SELFID,
					skuCode: $item.data('id'),
					qty: $item.find('.amount').data('amount') * (-1)
				}),
				success: function(res) {
					$item.remove();
				}
			});
		});
	}

	function saveCar (list, callback) {
		$.ajax({
			url: HOST + '/api/shopcart/sku/batchUpdate',
			type: 'post',
			data: JSON.stringify({
				openid: SELFID,
				skus: list
			}),
			success: function(res) {
				callback && callback(res.content);
			}
		});
	}

	function onBuy () {
		if(status == 'edit') {
			$.alert('保存购物车后再下单!');
			return;
		}
		if($('.active').length == 0) {
			$.alert('请选择商品!');
			return;
		}
		var details = [];
		var total = 0;
		$('.item_circle.active').forEach(function (item) {
			var $li = $(item).closest('li');
			var detail = cache[$li.data('id')];
			detail.qty = $li.find('.amount').data('amount');
			detail.spec = $li.find('.spec').html();
			total += (+detail.qty) * (+detail.current_price);
			details.push(detail);
		});
		sessionStorage.setItem('details', JSON.stringify(details));
		sessionStorage.setItem('total', total);
		window.location = './product_sure.html?from=car';
	}

	function onReturn () {
		if(param.from) {
			window.location = './product_cloth_info.html' + location.search;
			return;
		}
		window.location = './product_list.html';
	}

	function onLook (e) {
		var $target  = $(e.currentTarget);
		if($target.hasClass('item_edit')) {
			return;
		}
		window.location = './product_cloth_info.html?id='+$target.closest('.item').attr('data-id').slice(0, -3);
	}
});
